package GEMonitor;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import GEMonitor.em.MsgType;
import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class GEMsgDecoderServer extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        try {
            if (!in.isReadable()) {
                return;
            }

            byte soh = in.readByte();
            int length = 0;
            if (soh == 0x01) {
                length = Integer.parseInt(in.readCharSequence(4, CharsetUtil.US_ASCII).toString(), 16);
            } else if (soh == 0x02)  //sound
            {
                length = in.readInt();
            }
            String msg_type = in.readCharSequence(2, CharsetUtil.US_ASCII).toString();

            String systemID = in.readCharSequence(12, CharsetUtil.US_ASCII).toString();
            try {
                int content_len = length - 10 - systemID.length();
                byte[] content = new byte[content_len];
                if (content_len > 0) {
                    try {
                        in.readBytes(content);
                    } catch (Exception e) {
                        MyLogger.Error(systemID + "content转换异常:" + e.getMessage());
                    }
                }

                String check = in.readCharSequence(2, CharsetUtil.US_ASCII).toString();

                byte[] arr = new byte[length - 8];
                System.arraycopy(msg_type.getBytes(), 0, arr, 0, msg_type.length());
                if (systemID.length() > 0) {
                    System.arraycopy(systemID.getBytes(), 0, arr, 2, systemID.length());
                }
                if (content.length > 0) {
                    System.arraycopy(content, 0, arr, msg_type.length() + systemID.length(), content_len);
                }

                String chk = Helper.checksum(arr);
                if (!chk.equals(check)) {
                    MyLogger.Error(systemID + "校验和错误,应为:" + chk + ",实际为:" + check);
                    return;
                }

                byte etx = in.readByte();
                if (etx != 0x03) {
                    MyLogger.Error(systemID + "结束标志错误:" + etx);
                    return;
                }

                GEMsg msg = new GEMsg();
                msg.msg_type = msg_type;
                msg.systemID = systemID;

//                MyLogger.Info(systemID + " msgType:" + msg_type + ",content:" + HexUtil.encodeHexStr(content));


                msg.content = (
                        msg_type.equals(MsgType.REPORT_ENCRYPTED.getValue())
                                || msg_type.equals(MsgType.REPLY_ENCRYPTED.getValue())
                                || msg_type.equals(MsgType.HEART_BEAT.getValue())
                ) ? AesUtil.aesDecode(content) : content;

                if (msg_type.equals(MsgType.REPORT_ENCRYPTED.getValue())
                        || msg_type.equals(MsgType.REPLY_ENCRYPTED.getValue())
                        || msg_type.equals(MsgType.HEART_BEAT.getValue())) {
                    msg.content = AesUtil.aesDecode(content);
                } else if (msg_type.equals(MsgType.DEW_POINT_A.getValue()) || msg_type.equals(MsgType.DEW_POINT_B.getValue())) {
                    msg.content = getStr(content).getBytes();
                } else {
                    msg.content = content;
                }

                out.add(msg);
            } catch (Throwable t) {
                MyLogger.Error(systemID + ":decode错误");
                MyLogger.Error(t.getMessage());
                throw t;
            }
        } catch (Throwable t2) {
            MyLogger.Error("decode错误");
        }
    }

/*
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            // 统一的异常处理
        } finally {
            ReferenceCountUtil.release(cause);
        }
    }
 */

    private String getStr(byte[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i += 4) {
            float val = byte2Float(arr, i);
            sb.append(new BigDecimal(val).setScale(1, RoundingMode.HALF_UP).toString()).append(";");
        }
        return sb.toString();
    }

    // 从byte数组的index处的连续4个字节获得一个int
    private float byte2Float(byte[] arr, int index) {
        int l = (0xff000000 & (arr[index + 2] << 24)) |
                (0x00ff0000 & (arr[index + 3] << 16)) |
                (0x0000ff00 & (arr[index + 0] << 8)) |
                (0x000000ff & arr[index + 1]);
        return Float.intBitsToFloat(l);
    }

    public static void main(String[] args) {

        byte[] n = new byte[]{0x43, 0x31, 0x38, 0x39, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31,
                0x30, 0x30, 0x32, 0x75, (byte) 0x87, 0x62, 0x1c, 0x18, (byte) 0xa2, (byte) 0xa1, 0x47, 0x3a, (byte) 0xb7, 0x46, (byte) 0xc8, 0x6e,
                0x56, (byte) 0xe5, 0x5b, (byte) 0xf1, (byte) 0x9e, (byte) 0xcb, 0x13, 0x26, (byte) 0xa1, (byte) 0xd0, 0x59, 0x40, 0x16, 0x59, 0x15, 0x76,
                0x00, (byte) 0xba, 0x12, (byte) 0xf1, 0x17, 0x0b, 0x29, (byte) 0x88, (byte) 0xe7, (byte) 0x9c, 0x55, 0x65, 0x33, 0x06, (byte) 0xf4, 0x51,
                0x2f, (byte) 0xec, 0x0a, (byte) 0xab, 0x2f, 0x71, (byte) 0xff, 0x55, (byte) 0xb5, (byte) 0xe7, (byte) 0xac, (byte) 0xaf, (byte) 0xd7, (byte) 0x91, (byte) 0xa3, 0x47,
                (byte) 0xb4, 0x65, 0x2b, (byte) 0xa4, (byte) 0x8a, 0x6d, (byte) 0xe6, 0x2e, (byte) 0xf3, (byte) 0xf5, 0x0a, (byte) 0xd6, 0x64, (byte) 0xec, 0x4d, 0x2c,
                0x35, 0x3b, 0x74, 0x2a, (byte) 0x92, 0x4a, 0x06, 0x41, (byte) 0xe5, 0x7a, (byte) 0xfd, (byte) 0xa9, (byte) 0xbb, 0x17, (byte) 0xfa, (byte) 0xa9,
                (byte) 0xd0, (byte) 0x94, 0x72, (byte) 0xc9, 0x1a, 0x4e, (byte) 0xfa, 0x02, (byte) 0xc6, 0x29, 0x42, (byte) 0xf7, (byte) 0x90, (byte) 0xa7, 0x3a, (byte) 0x8c,
                (byte) 0xbf, 0x36, (byte) 0xdd};

//        char *buf = (char *)packet + 5;
//        int  checkLen = 126;
//        uint8_t checkSum[2] = {0};
        System.out.println("length:;" + n.length);

        System.out.println("checkSum:0x%x,0x%x;" + Helper.checksum(n));


    }
}